package com.o2o.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.o2o.content.FileContent;

public class FileUtil {
	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	public static String getFileContentType(File file) {
		FileInputStream is;
		String type = FileContent.UNKNOWN;
		try {
			is = new FileInputStream(file);
			byte[] b = new byte[3];
			is.read(b, 0, b.length);
			String fileHeader = bytesToHexString(b).toUpperCase();
			if (fileHeader.equals(FileContent.JPEG)) {
				type = FileContent.JPEG;
			}
			if (fileHeader.equals(FileContent.GIF)) {
				type = FileContent.GIF;
			}
			if (fileHeader.equals(FileContent.PNG)) {
				type = FileContent.PNG;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return type;
	}

	private static final int FILE_SIZE = 16 * 1024;

	public static boolean saveFile(File source, String path) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(source), FILE_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(path),
					FILE_SIZE);
			// in-->image-->out
			byte[] image = new byte[FILE_SIZE];
			while (in.read(image) > 0) {
				out.write(image);
			}
			return true;
		} catch (IOException ex) {
			ex.printStackTrace();
			return false;
		} finally {
			try {
				in.close();
				out.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 获取文件后缀名
	 * 
	 * @param filename
	 * @return
	 */
	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}
}
